<template>
  <ContentWrap>
    <!-- 顶部查询项 -->
    <el-form :model="form" inline>
      <el-form-item label="位置">
        <el-select
          filterable
          style="width: 170px"
          v-model="form.position"
          placeholder="请选择位置"
          clearable
        >
          <el-option
            v-for="item in positionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作项 -->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd"> 新增 </el-button>
      <el-button type="danger" @click="handleDelete('Bulk', {})"> 批量删除 </el-button>
    </div>

    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" prop="id" min-width="80" />
      <el-table-column label="商品名称" prop="pm_id" min-width="120" />
      <el-table-column label="位置" prop="position_value" min-width="100" />
      <el-table-column label="排序" prop="sort" min-width="100" />
      <el-table-column label="创建时间" prop="create_time" min-width="180" />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="{ row }">
          <el-button @click="handleDelete('single', row)" size="small" type="danger">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />

    <!-- 新增/编辑弹框 -->
    <Add ref="dialogRef" @refresh="initialize" />
  </ContentWrap>
</template>

<script setup lang="ts">
import Add from './Add.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { getListApi, deleteApi, getEnumApi } from '@/api/recommendProduct'
import type {
  RecommendProductListResponse,
  ApiResponse,
  DeleteParams
} from '@/api/recommendProduct/types'

// 定义组件名称
defineOptions({
  name: 'RecommendProductPage'
})

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const dialogRef = ref()
const paginationTotal = ref<number>(0)

const form = ref<Record<string, any>>({
  position: undefined,
  pageIndex: 1,
  pageSize: 20
})

// 位置选项
const positionOptions = ref<any[]>([])

// 批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 点击新增
const handleAdd = () => {
  nextTick(() => {
    dialogRef.value.getBackShow('add')
    dialogRef.value.dialogVisible = true
  })
}

// 点击删除
const handleDelete = (type: string, row: Record<string, any>) => {
  const ids = type === 'single' ? [row.id] : multipleSelection.value.map((item) => item.id)
  if (type === 'Bulk' && !ids.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  ElMessageBox.confirm('确定要删除选中的数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = (await deleteApi({ ids } as DeleteParams)) as ApiResponse<any>
        if (res.code === 0) {
          ElMessage.success('删除成功')
          await initialize()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 获取枚举数据
const getEnumData = async () => {
  try {
    const res = await getEnumApi()
    if (res.code === 0) {
      positionOptions.value = res.data.position || []
    }
  } catch (error) {
    console.error('获取枚举数据失败', error)
  }
}

// 初始化请求
const initialize = async () => {
  try {
    tableLoading.value = true
    const res = (await getListApi({
      position: form.value.position,
      pageIndex: form.value.pageIndex,
      pageSize: form.value.pageSize
    })) as ApiResponse<RecommendProductListResponse>

    if (res.code === 0 && res.data) {
      dataList.value = res.data.list || []
      paginationTotal.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取列表失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('获取列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 重置查询项
const reset = () => {
  form.value = {
    position: undefined,
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getEnumData()
  initialize()
})
</script>

<style lang="less" scoped>
.m-1 {
  margin: 2px;
}
</style>
